<template>
	<view class="chat-container">
		<view class="bgF3F3F3"></view>
		<!-- <view class="flex-ju-c">
			<image class="wh260-260 ra260 mt50" src="/static/aaa.png"></image>
		</view>
		<view class="flex-ju-c mt30">
			<view class="pg25 bgF3F3F3 size22 width600">
				可以回答你的问题，什么问题都可以，政策、生活、经济的都可以，你可以把问题通过输入框发给我。来开启第一个话题吧：
			</view>
			<view>
				{{content}}
			</view>
		</view> -->
		<!-- <view class=" width1000">
			<view class="posifi width1000  flex1 bottom0 flex-ju-b zindex50 bgfff">
				<view class="flex-ju-b flex1 pg30  mg30 ra20 bnde">
					<input v-model="msgcon" class="flex1"  placeholder="发消息...." />
					<image @click="send" src="/static/send.png" mode="widthFix" class="width52"></image>
				</view>
			</view>
		</view> -->
		
			<!-- <view class="con   message-list" >
				<view v-for="(item,index) in arr" class="flex mt30" :style="{flexDirection:index % 2==0 ?'row-reverse':''}">
					<image class="wh100-100 ra100" src="/static/aaa.png"></image>
					<view class="mt15 mr15">
						<view style="max-width: 400rpx;" class="bgF3F3F3 ra15 pg20">{{item.title}}</view>
					</view>
				</view>
			</view> -->
			<view class="con message-list" >
				<view v-for="(item,index) in arr" :key="index" class=" mt30" >
					<view v-if="item.role=='user'" class="mt15 mr15 flex1 flex" style="flex-direction: row-reverse;">
						<view  style="max-width: 400rpx;" class="bg1580E7 colorfff ra15 pg20">{{item.content}}</view>
					</view>
					<template  v-else>
					<!-- 	<view  class="mt25 mr15 flex1 flex" style="flex-direction:row;">
							
							<view  :class="item.okloading?'bgF3F3F3 ra15 pg20':''">
								<view >
									<view v-if="item.okloading" class="flex-a-i ">
										思考中 
										<button class="butf bbt" style="padding:0;margin: 0;line-height: 0;" :loading="loading"></button>
									</view>
									<text class="pt15" selectable="true">{{item.thats}}</text>
								</view>
							</view>
							
						</view>
						<view  class="mt25 mr15 flex1 flex" style="flex-direction:row;">
							<view  class=" ra15 ">
								<text  selectable="true">{{item.content}}</text>
							</view>
						</view> -->
						
						<view class="mt20 mr15 flex1 flex" style="flex-direction:row;">
							<view  class=" ra15 bgF3F3F3 pg20">
								<text v-if="item.content"  selectable="true">{{item.content}}</text>
								<button v-else class="butf bbt" style="padding:0;margin: 0;line-height: 0;" :loading="loading"></button>
							</view>
						</view>
					</template>
					
					
					
				</view>
			</view>
			
			
				<view class="flex-ju-b zindex50 bgfff">
					<view class="flex-ju-b flex1 pg30  mg30 ra20 bnde">
						<input v-model="msgcon" class="flex1"  placeholder="发消息...." />
						<image @click="send" v-show="!loading" src="/static/send.png" mode="widthFix" class="images width52"></image>
						<button class="butf" v-show="loading" :loading="loading"></button>
					</view>
				</view>
	</view>
</template>

<script>
	import * as TextEncoding from "text-encoding-shim";
	const decoder = new TextEncoding.TextDecoder("utf-8");
	

	export default {
		data() {
			return {
				message:"",
				okloading:false,
				loading:false,
				index:0,
				content:"",
				arr:[],
				msgcon:"",
				a:0,
				record:[],
				tindex:0,
				id:"4",
				contents:"",
				page:1
			}
		},
		mounted() {
			
			if(uni.getStorageSync('record')){
				this.record=uni.getStorageSync('record')
				this.tindex = this.record.length
			}else{
				uni.setStorageSync('record',[])
			}
			
		},
		onPullDownRefresh() {
			this.page++
			this.getlist()
		},
		onLoad(option) {
			this.id=option.index
			if(option.index>0){
				this.getlist()
			}
		},
		methods: {
			   getlist(){
				   this.http('ai/session/'+this.id,{
				   	 page:this.page,
				   	 limit:26
				   }).then(res=>{
				   	  this.arr = [...this.arr,...res.data.messages]
					  uni.stopPullDownRefresh();
				   })
			   },
			   isValidJSON(str) {
			       try {
			           JSON.parse(str);
			           return true;
			       } catch (e) {
			           return false;
			       }
			   },
			send(){
				
				if(this.msgcon==''){
					uni.showToast({
						title:"输入你想问的",
						icon:'none'
					})
					return
				}
				
				 this.okloading = false
				   this.content=''
				   this.contents=''
				    
					this.arr.unshift({
						content:this.msgcon,
						role:'user'
					})
				    this.loading = true
					const requestTask = wx.request({
					    url: this.apiurl+'ai/knowledge_qa',
					    data: {
					        question:this.msgcon,
					      	session_id:this.id
					    },
						enableHttp2: false,
						timeout:300000,
						enableChunked:true,
						responseType: 'arraybuffer',
						method:'post',
					    header: {
							 "Accept": 'text/event-stream',
					         "Content-Type":"application/json",
							'Authori-zation':'Bearer '+( uni.getStorageSync("token") ? uni.getStorageSync("token") : '')
					    },
						success:res=>{
						}
					});
					this.arr.unshift({
						okloading:'1',
						content:this.content,
						role:'assistant'
					})
					this.msgcon = ''
					requestTask.onChunkReceived((chunk) => {
						 this.msgcon=''
						 const data = decoder.decode(new Uint8Array(chunk.data));
						 if (data.startsWith('data:')) {
							 var aa = data.replace(/data:/g, '').trim()
							 var s = aa.split('\n')
							  var arr =[]	
							 s.map(item=>{
								 
								 if(this.isValidJSON(item)&&item.length>10){
										if(JSON.parse(item).choices[0].delta.content){
											this.content+=JSON.parse(item).choices[0].delta.content
										}
										if(JSON.parse(item).choices[0].delta.reasoning_content){
											this.contents+=JSON.parse(item).choices[0].delta.reasoning_content
										}
								 }else{
									 if(item.length>1){
										 // console.log(item,"bbbb11")
									 }
								 }
								 
								 // if(item.length>10){
									// if(JSON.parse(item).choices[0].delta.content){
									// 	this.content+=JSON.parse(item).choices[0].delta.content
									// }
									// if(JSON.parse(item).choices[0].delta.reasoning_content){
									// 	this.contents+=JSON.parse(item).choices[0].delta.reasoning_content
									// }
								 // }
								 
								 if(item.indexOf('end')!= -1 || item.indexOf('stop')!= -1){
									this.loading = false
								 }
							 })
							 if(this.contents){
								 this.okloading = true
								 this.$set(this.arr[0],'thats',this.contents)
								 this.$set(this.arr[0],'okloading',true)
							 }
							if(this.content){
								
							 	this.$set(this.arr[0],'content',this.content)
							}
						 }
					});
				
				
				
				
				
				//this.http('ai/createSession',{},'post').then(res=>{
					// this.http('ai/knowledge_qa',{
					// 	question:"在吗",
					// 	// session_id:res.data.session_id
					// 	session_id:3
					// },'post').then(res=>{
					// }).catch(res)
					
				//})
				
				
			
				
				
				
				
			// 	this.arr.unshift({
			// 		title:this.msgcon,
			// 		that:this.content
			// 	})
				
			// 	const requestTask = wx.request({
			// 	    url: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
			// 	    data: {
			// 	        "model": "doubao-seed-1-6-250615",
			// 			"messages": [
			// 			      {
			// 			        "role": "user",
			// 			        "content": this.msgcon
			// 			      }
			// 			    ],
			// 			    "stream": true
			// 	    },
			// 		enableChunked:true,
			// 		responseType: 'arraybuffer',
			// 		method:'post',
			// 	    header: {
			// 			"Accept": 'text/event-stream',
			// 	        "Content-Type":"application/json",
			// 			"Authorization":"Bearer cf8eb38f-ea48-4c11-a925-979a0cd61ad9" 
			// 	    }
			// 	});
			// 	requestTask.onChunkReceived((chunk) => {
					
			// 		this.loading = true
			// 		this.msgcon=''
			// 		const data = decoder.decode(new Uint8Array(chunk.data));
			// 		var aa = data.replace(/data: /g, '').trim()
			// 		var s = aa.split('\n')
			// 		var arr =[] 
			// 		s.map(item=>{
			// 			if(item.indexOf('reasoning_content')!= -1){
			// 				this.content+=JSON.parse(item).choices[0].delta.reasoning_content
			// 			} else if(item.indexOf('finish_reason')!= -1){
			// 				this.content=''
			// 				this.loading = false
			// 				this.record[this.tindex]=this.arr
			// 				uni.setStorageSync('record',this.record)
			// 			}
			// 		})
			// 		if(this.content){
			// 			this.$set(this.arr[0],'that',this.content)
			// 		}
					
					
			// 	});
			
			}
		}
	}
</script>

<style>
	
	/deep/ uni-button:after,button:after {
		border:none;
	}
	
	
	.butf{
		background: none;
	}
	
	.chat-container {
	  display: flex;
	  flex-direction: column;
	  height:98vh;
	  /* padding-bottom: env(safe-area-inset-bottom); */
	}
	.message-list {
		flex: 1;
	  display: flex;
	  flex-direction: column-reverse; /* 关键属性 */
	  overflow-y: auto;
	}
	
	page{
		background: #fff;
	}
	.bnde{
		box-shadow: 0rpx 6rpx 13rpx 0rpx rgba(28,48,75,0.18);
	}
</style>
